package com.core.common.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @program: kuntail
 * @description:
 * @author: honglei
 * @create: 2022-03-21 17:31
 */

public class JwtUtil {


    private static String salt="salt";


    private static final long  TIME_OUT= 60 * 1000*60*24;



    /**
     * 设置认证token
     *      id:用户id
     *      subject:用户名
     */
    public static String createJwt(String id, String name, Map<String,Object> map) {

        long expirationTime = System.currentTimeMillis() + TIME_OUT;
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(map)
                .setId(id)
                .setSubject(name)
                .setIssuedAt(new Date())
                .setExpiration(new Date(expirationTime))
                .signWith(SignatureAlgorithm.HS256, salt);
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 解析token字符串获取clamis
     */
    public static Claims parseJwt(String token) {
        Jws<Claims> claimsJws  = Jwts.parser().setSigningKey(salt).parseClaimsJws(token);
        Claims claims=claimsJws .getBody();
        return claims;
    }

    /**
     * 解析token字符串获取clamis
     */
    public static String getId(String token) {
        return Jwts.parser().setSigningKey(salt).parseClaimsJws(token).getBody().getId();
    }


    public static boolean validateToken(String token){
        if (Objects.isNull(token)){
            return false;
        }
        return Objects.nonNull(parseJwt(token));
    }
}
